from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

class File(db.Model):
  content = db.StringProperty(multiline=True)
  name = db.StringProperty()
  owner = db.UserProperty()
  created = db.DateTimeProperty(auto_now_add = True)
  mtime = db.DateTimeProperty(auto_now = True)

class MainPage(webapp.RequestHandler):
  def get(self):
    self.response.out.write(template.render('vigor.html', {'single': False}))

class Writer(webapp.RequestHandler):
  def post(self):
    content = self.request.get('content')
    filename = self.request.get('filename')
    user = users.get_current_user()
    if user and filename:
      files = File.all()
      files.filter('user =', user).filter('name = ', filename);
      for user_file in files:
        user_file.content = content
        user_file.put()
        break
      else:
        user_file = File(name=filename, owner=user, content=content);
        user_file.put()
      self.response.out.write('success')
    elif not user:
      self.response.out.write('<a href="%s">Sign in</a> to save files.'
          % users.create_login_url('/') )

class Reader(webapp.RequestHandler):
  def get(self):
    filename = self.request.get('filename')
    user = users.get_current_user()
    if user and filename:
      files = File.all()
      files.filter('owner =', user).filter('name = ', filename);
      content = None
      for user_file in files:
        content = user_file.content
      if not content == None:
        self.response.out.write('success:' + content)
      else:
        self.response.out.write('File not found.');
    elif not user:
      self.response.out.write('<a href="%s">Sign in</a> to open files.'
          % users.create_login_url('/') )

application = webapp.WSGIApplication([('/', MainPage),
                                      ('/write', Writer),
                                      ('/read', Reader),
                                      ], debug=True)

def main():
  run_wsgi_app(application)

if __name__ == '__main__':
  main()
